package game.socket;

import game.system.CmdThread;
import game.system.Config;
import game.utils.DES;
import game.utils.DateUtils;
import game.utils.PropertiesUtils;
import game.utils.SystemUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

import org.apache.log4j.Logger;

public class GameServer {
	protected static Logger log = Logger.getLogger(GameServer.class);
	
	public static void main(String[] args) {
		CmdThread ct = new CmdThread();
		ct.start();
		
		GameServer server = new GameServer();
		server.start();
	}
	
	private static int PORT = 8089;//默认8089
	private static int maxSocket = 10000;//0为无限
	
	public static int getPort(){
		return PORT;
	}
	
	public GameServer(){
		Map config = PropertiesUtils.getMapByAbsPath("system_config.properties");
		try {
			PORT = Integer.parseInt(config.get("port").toString());
		} catch (Exception e) {
			log.error("系统端口读取配置文件失败",e);
		}
	}
	
	public void start(){
		try {
			log.info("开始启动game服务...");
			ServerSocket serverSocket = new ServerSocket(PORT);
			log.info("启动game服务成功,端口："+PORT);
			
			Socket socket = null;
			GameThread gameThread = null;
			while(true){
				log.debug("等待客户端连接...");
				socket = serverSocket.accept();
				if(GameThread.getGameThreads().size() > maxSocket){
					sendMaxSocket(socket);
					socket.close();
					log.error("超过最大连接数");
					System.out.println("超过最大连接数,当前系统最大连接数为"+maxSocket+",请更新授权文件");
					continue;
				}
				log.debug("有客户端连接，IP:"+socket.getInetAddress().toString());
				gameThread = new GameThread(socket);
				gameThread.start();
				gameThread = null;
				socket = null;
				log.debug("客户端线程启动成功！！！");
			}
		} catch (IOException e) {
			log.error("异常",e);
		}
	}
	
	private static final String MSG_MAX_SOCKET = "alert?message=超过最大连接数,请稍后连接\0";
	private void sendMaxSocket(Socket socket){
		OutputStreamWriter osw;
		try {
			osw = new OutputStreamWriter(socket.getOutputStream());
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(MSG_MAX_SOCKET);
			bw.flush();
			bw.close();
			osw.close();
		} catch (IOException e) {
			log.error("异常：发送超过最大连接数",e);
		}
	}
	
	static{
		try {
			InputStream is = GameServer.class.getResourceAsStream("/authorize.key");
			java.io.InputStreamReader isr = new java.io.InputStreamReader(is);
			java.io.BufferedReader br = new BufferedReader(isr);
			String tmp = null;
			StringBuffer strMi = new StringBuffer();
			while((tmp=br.readLine())!=null){
				strMi.append(tmp);
			}
			br.close();
			isr.close();
			is.close();
			String[] attrs = new DES().getDesString(strMi.toString()).split("&");
			Map params = new java.util.HashMap(attrs.length);
			for(String attr : attrs){
				String[] kv = attr.split("=");
				params.put(kv[0], kv.length==2?kv[1]:null);
			}
			
			String authorizeKey = Config.get("authorize.key");
			if(authorizeKey == null){
				
				//开辟线程，发送邮件到邮箱   信息包含ip  等等
			}
			
			long maxDate = Long.parseLong(params.get("maxDate").toString());
			int ms = Integer.parseInt(params.get("maxSocket").toString());
			String physicalAddress = params.get("physicalAddress").toString();
			
			if(!strMi.toString().equals(authorizeKey)){
				System.out.println("无授权文件或者授权文件错误,只能试用版配置运行,请更新授权文件");
			}else if(System.currentTimeMillis() > maxDate){
				System.out.println("超过最大使用日期,只能试用版配置运行,请更新授权文件");
			}else if(!SystemUtils.getPhysicalAddress().equals(physicalAddress)){
				System.out.println("非绑定主机,只能试用版配置运行,请更新授权文件");
			}else{
				maxSocket = 100;
				System.out.println("已授权,最大使用日期:"+ DateUtils.toDate(maxDate) +"      最大客户端连接数:"+ms);
			}
		} catch (Exception e) {
			System.out.println("无授权文件或者授权文件错误,只能试用版配置运行,请更新授权文件");
		}
		
	}
}
